<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var lastStoneWeightII = function (stones) {
      let sum = 0
      stones.forEach(element => sum += element)
      let half = sum >> 1
      let dp = new Array(half + 1).fill(0)
      for (let stone of stones) {
        for (let j = half; j >= stone; j--) {
          dp[j] = Math.max(dp[j], dp[j - stone] + stone)
        }
      }
      return sum - dp[half] * 2
    };
    console.log(lastStoneWeightII([2, 7, 4, 1, 8, 1]))
  </script>
</body>

</html>